import PropTypes from 'react-router/lib/PropTypes'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

import * as AddAction from '../actions/add'

import { Row, Col, Tabs, Form, Button, Input, Modal, Icon, Spin, Popover, message } from 'antd'
const FormItem = Form.Item;

import Immutable from 'immutable'
const is = Immutable.is;

import {
  WeaReqTop,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaRichText,
  WeaInput,
} from 'ecCom'

import '../css/detail.less'

class Add extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      richValue: '',
      status: '',
      richHeight: 0,
      rightMenus: [
        {
    	    type: 'submit',
    	    menuName: '提交',
    	    menuIcon: 'icon-coms-help',
    	  },
    	  {
    	    type: 'draft',
    	    menuName: '草稿',
    	    menuIcon: 'icon-coms-help',
    	  },
      ],
    }
    this.onTabsChange = this.onTabsChange.bind(this);
    this.onToolsChange = this.onToolsChange.bind(this);
    this.doSubmit = this.doSubmit.bind(this);
    this.extentsConfig = [
      '-',
      {
        name: 'Upload',  //上传类型组件
        show: <Icon type="paper-clip" title='上传附件' />,
        uploadUrl: `/api/doc/upload/uploadFile?model=reply&docid=`, //上传地址
        category: '/api/doc/upload/uploadFile?model=reply',//文档目录
      },
      {
        name: 'Browser', //浏览按钮组件，浏览按钮类型及其他属性按照浏览按钮说明
        show: <i className='icon-coms-Journal' title='文档' />,
        type: '37', //浏览按钮类型
        title: '文档', //浏览按钮标题
      },
      {
        name: 'Browser', //浏览按钮组件，浏览按钮类型及其他属性按照浏览按钮说明
        show: <i className='icon-coms-Workflow-o' title='流程' />,
        type: '152', //浏览按钮类型
        title: '流程', //浏览按钮标题
      },
    ]
  }
  componentDidMount() {
    //一些初始化请求
    let { actions } = this.props,
      richHeight = document.documentElement.clientHeight - $(".wea-new-top-req-content").offset().top - 137;
      this.setState({ richHeight });
  }
  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    //点击菜单路由刷新组件
    if(keyOld !== keyNew) {

    }
    //设置页标题
//  if(window.location.pathname.indexOf('/spa/document/') >= 0 && !is(this.props.basicInfo, nextProps.basicInfo) && nextProps.basicInfo.get('docSubject') && document.title !== nextProps.basicInfo.get('docSubject'))
//    document.title = nextProps.basicInfo.get('docSubject');
  }
  shouldComponentUpdate(nextProps, nextState) {
    //组件渲染控制
    return true
  }
  componentWillUnmount() {
    //组件卸载时一般清理一些状态

  }
  render() {
    let { loading, tabKey, actions } = this.props,
      { richValue, richHeight } = this.state;
    return (
      <div className='wea-doc-detail wea-doc-add'>
        <WeaRightMenu datas={this.getRightMenu()}>
          <WeaReqTop
            title={<span style={{ marginLeft: 8 }}><WeaInput placeholder='文档标题' style={{ width: 455 }} viewAttr='3' onChange={v => console.log(v)} /></span>}
            loading={loading}
            icon={<i className='icon-coms-doc' />}
            iconBgcolor='#df583a'
            replaceTab={
              <Tabs 
                activeKey={tabKey}
                onChange={this.onTabsChange} 
              >
                { this.getTabPane() }
              </Tabs>
            }
            buttons={this.getButtons()}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick.bind(this)}
          >
            <div className='wea-doc-detail-content'>
		          <div className='wea-doc-detail-content-inner'>
		            { richHeight ? 
		              <WeaRichText
		                ref='doc_add'
		                value={richValue}
		                ckConfig={{
		                  toolbar:[
		                    { name: 'document', items: [ 'Source'] },
		                    { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
		                    { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
		                    { name: 'colors', items: [ 'TextColor' ] },
			                  { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
			                  { name: 'links', items: [ 'Link', 'Unlink' ] },
			                  { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] },
			                  { name: 'clipboard', items: [ 'Undo', 'Redo' ] },
			                  { name: 'tools', items: [ 'Maximize' ] },
			                ],
			                height: richHeight,
			                uploadUrl: `/api/doc/upload/uploadFile?model=reply&docid=`,
			              }}
			              extentsConfig={this.extentsConfig}
			              onChange={v=>this.setState({richValue: v})}
			              onStatusChange={s => this.setState({status: s})}
			              onToolsChange={this.onToolsChange}
			            /> : null
		            }
		          </div>
            </div>
          </WeaReqTop>
        </WeaRightMenu>
      </div>
    )
  }
  // tab
  getTabPane(){
    let tabInfo = [
    	{
    		key: '0',
    		value: '正文内容',
    	},
    	{
    		key: '1',
    		value: '文档属性',
    	},
    	{
    		key: '2',
    		value: '文档附件',
    	},
    ]
    return tabInfo.map(data => {
      return <Tabs.TabPane tab={data.value} key={data.key} />
    })
  }
  onTabsChange(key){
    let { actions } = this.props;
    actions.setTabKey(key);
  }
  // 右键菜单
  getButtons(){
    let { rightMenus } = this.state,
      btnArr = [];
    rightMenus.map(btn => {
      btnArr.push(<Button type="primary" onClick={()=> this.onRightMenuClick(btn.type)}>{btn.menuName}</Button>);
    });
    return btnArr
  }
  getRightMenu(){
    let { rightMenus } = this.state,
      btnArr = [];
    rightMenus.map(btn => {
      btnArr.push({
        key: btn.type,
        icon: <i className={btn.menuIcon}/>,
        content: btn.menuName,
        onClick: key => this.onRightMenuClick(key)
      });
    });
    return btnArr
  }
  onRightMenuClick(key){
    let { rightMenus } = this.props;
    // console.log('key: ', key)
  }
  
  //文档属性
  getAttr(){
    let { attrDatas } = this.props,
      items = [];
    attrDatas.map((item, i) => {
      let col = item.get('column') || 1;
      items.push(
        <Col span={12 * col}>
          <FormItem 
            label={item.get('label')}
            labelCol={{span: 6 / col }}
            wrapperCol={{span: 24 - 10 / col}}
          >
            <div className='wea-doc-detail-content-inner-attr-value' dangerouslySetInnerHTML={{__html: item.get('value')}}/>
          </FormItem>
        </Col>
      )
    })
    return (
      <Row className='wea-doc-detail-content-inner-attr'>
        {items}
      </Row>
    )
  }
  // 回复
  getReply(){
    let { actions } = this.props,
      { docid, richVisible, richValue, status } = this.state;
    return (
      <div className='wea-doc-detail-reply'>
        { this.getReplyList() }
        <div className='wea-doc-detail-reply-rich' style={{padding: richVisible ? 0 : 10 }}>
          <div style={{ display: richVisible ? 'none' : 'block' }} onClick={() => { this.setState({richVisible: true}); this.refs.reply_main.getEditor().focus()}}>
            <i className='icon-coms-edit' /> 写回复
          </div>
          <div style={{ display: richVisible ? 'block' : 'none' }}>
            <WeaRichText
              ref='reply_main'
              value={richValue}
              ckConfig={{
                toolbar:[
                  { name: 'document', items: [ 'Source'] },
                  { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
                  { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
                  { name: 'colors', items: [ 'TextColor' ] },
                  { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
                  { name: 'links', items: [ 'Link', 'Unlink' ] },
                  { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] },
                  { name: 'clipboard', items: [ 'Undo', 'Redo' ] },
                ],
                height:100,
                uploadUrl: `/api/doc/upload/uploadFile?model=reply&docid=${docid}`,
              }}
              extentsConfig={this.extentsConfig}
              onChange={v=>this.setState({richValue: v})}
              onStatusChange={s => this.setState({status: s})}
              onToolsChange={this.onToolsChange}
            />
            {
              status === 'ready' &&
              <div className='wea-doc-detail-reply-rich-btm'>
                <Button type='primary' onClick={() => {
                	if(richValue) {
                  	let { Upload_image, Upload_file, Browser_152, Browser_37 } = this.state;
                  	this.doSubmit({ docid, content: richValue, replyid: '' }, 0, Upload_image, Upload_file, Browser_152, Browser_37)
                    this.setState({richValue: '', richVisible: false})
                  }else{
                    message.warning('回复内容不能为空！')
                  }
                }}>提交</Button>
                <Button style={{marginLeft: 8}} type='ghost' onClick={()=>this.setState({richValue: '',richVisible: false})}>取消</Button>
              </div>
            }
          </div>
        </div>
      </div>
    )
  }
  doSubmit(params, hasMore, Upload_image, Upload_file, Browser_152, Browser_37){
    let { actions } = this.props,
      { content } = params;
    if(Upload_image){
      let { ids, names } = this.extentsfilter(content, Upload_image);
      params.imgFileids = ids;
      params.imgFilenames = names;
    }
    if(Upload_file){
      let { ids, names } = this.extentsfilter(content, Upload_file);
      params['field-annexupload'] = ids;
      params['field-annexupload-name'] = names;
    }
    if(Browser_152){
      let { ids, names } = this.extentsfilter(content, Browser_152);
      params.signworkflowids = ids;
      params.signworkflownames = names;
    }
    if(Browser_37){
      let { ids, names } = this.extentsfilter(content, Browser_37);
      params.signdocids = ids;
      params.signdocnames = names;
    }
    actions.saveReply(params, hasMore);
  }
  extentsfilter(content, list){
    let ids = [],
      names = [],
      _list = list.filter(item => content.indexOf(item.string) >= 0);
    _list.map(item => {
      ids.push(item.fileid || item.id)
      names.push(`////~~${item.filename || item.name}~~////`)
    })
    return { ids: ids.join(','), names: names.join('') }
  }
  onToolsChange(name = '', ids = '', list = [], type = ''){
    let stateList = this.state[`${name}_${type}`],
      mirror = {
        37: "doc",
        152: "workflow",
      },
      newList = list.map(item => {
        let _item = { ...item };
        if(name === 'Upload' && type === 'image') {
          _item.string = `=${_item.fileid}`;
        }else if(name === 'Upload' && type === 'file') {
          _item.string = `=${_item.fileid}`;
        }else if(name === 'Browser') {
          _item.string = `,${item.id},`;
        }
        return _item
      });
    this.setState({ [`${name}_${type}`] : (stateList ? stateList.concat(newList) : newList) })
    return Util.transfStr(name, ids, list, type);
  }
}

//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return(
      <WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
    );
  }
}

Add = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(Add);

//form 表单与 redux 双向绑定
//Add = createForm({
//  onFieldsChange(props, fields) {
//    props.actions.saveFields({ ...props.fields, ...fields });
//  },
//  mapPropsToFields(props) {
//    return props.fields;
//  }
//})(Add);


// 把 state map 到组件的 props 上
const mapStateToProps = state => {
  const { documentAdd } = state;
  return { 
    loading: documentAdd.get('loading'),
    rightMenus: documentAdd.get('rightMenus'),
    tabKey: documentAdd.get('tabKey'),
    tabInfo: documentAdd.get('tabInfo'),
  }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
  return {
    actions: bindActionCreators(AddAction, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Add);